package my.diplom.dao.impl;

import my.diplom.dao.ICategoryDAO;
import my.diplom.entity.Category;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.orm.hibernate3.HibernateTemplate;

/**
 * Created by IntelliJ IDEA.
 * User: gb
 * Date: 14.07.2009
 * Time: 15:09:56
 * To change this template use File | Settings | File Templates.
 */
public class CategoryDAOImpl implements ICategoryDAO {

    private static final Logger log = Logger.getLogger(CategoryDAOImpl.class);

    private HibernateTemplate template;

    public void setTemplate(HibernateTemplate template) {
        this.template = template;
    }


    public void create(Category category) {
        log.debug("create category" + category.getCategoryName());
        template.save(category);
    }

    public void update(Category category) {
        log.debug("update category" + category.getCategoryName());
        template.saveOrUpdate(category);
    }

    public Category getById(Long categoryId) {
        log.debug("get category by id = " + categoryId);
        return (Category) template.get(Category.class, categoryId);
    }


    public Category getById(Long categoryId, boolean initApplications) {
        log.debug("get category by id = " + categoryId);
        Category category = (Category) template.get(Category.class, categoryId);
        if (initApplications){
            template.initialize(category.getApplications());
            template.initialize(category.getStatus());
        }
        return category;
    }

    public List<Category> getAll() {
        log.debug("get all categories");
        //noinspection JpaQlInspection
        return template.find("from Category order by categoryName");
    }

    public Category getByName(String categoryName) {
        log.debug("get category by name = " + categoryName);
        //noinspection JpaQlInspection
        return (Category) (template.find("from Category c where c.categoryName = ?", categoryName).get(0));
    }

    public void delete(Category category) {
        log.debug("delete category" + category.getCategoryName());
        template.delete(category);
        template.flush();
    }


    @Override
    public List<Category> getAllActive() {
        log.debug("get all active categories");
        //noinspection JpaQlInspection
        return template.find("select c from Category c , Status s where c.status = s and s.statusName = 'active' order by categoryName");
    }
}
